/*
 * Copyright 2011 CraneLeeon authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var Page_UserMgt = function(){
    var colModel;
    var UserMgt_list;
    var lastsel;

    //autosync functions
    var runAutoSync = true;
    var autoSyncStarted = false;
    var timeoutId;
    function setRunAutoSync(b){
        runAutoSync = b;
        if(!runAutoSync && timeoutId){
            window.clearTimeout(timeoutId);
            autoSyncStarted = false;
        } else{
            if(SYNC_CALLBACK_STACK.autoSyncFlag == 'n_Security_UserMgt' && !autoSyncStarted){
                autoSyncStarted = true;
                timeoutId = window.setTimeout(function(){
                    autoSyncStarted = false;
                    if(runAutoSync){
                        UserMgt_list.jqGrid().trigger("reloadGrid");
                    }
                },5000);
            }
        }
    }
    this.setRunAutoSync = setRunAutoSync;
    //----------

    this.init = function(){
        colModel = new ColModel();
        colModel.titles = [//TODO: modify column titles
                lbl_UserName,
                lbl_Password

        ];
        colModel.model = [//TODO: modify colum define
                {name:'name',index:'name', width:100,editable:true,editrules:{custom:true, custom_func:vld_username}},
                {name:'password',index:'password', edittype:'password',width:100,editable:true,editrules:{custom:true, custom_func:vld_password}}
        ];
        UserMgt_list = $('#UserMgt_list').jqGrid({
            url:'Service.action?act='+ACT_LIST
                +'&boClass=org.crane.webtemplate.model.security.User'
                +'&fieldsForList='+colModel.getFields(),
            width: $('#TabContainer').width() - 39,
            height: '100%',
//            height: $('#TabContainer').height() - 125,
            datatype: 'json',
            multiselect: true,
            rowNum:10,
            rowList:[5,10,20,25],
            pager: '#UserMgt_pager',
            sortname: 'name',
            sortorder: 'asc',
            viewrecords: true,
//            caption:'&nbsp;',
            colNames:colModel.titles,
            colModel:colModel.model,
            editurl: 'security/UserMgt.action?act='+ACT_SAVE,
            ondblClickRow: editRow


        });
        UserMgt_list.jqGrid(
            'navGrid',
            '#UserMgt_pager',
            {edit:false,add:false,del:false}
        );

        UserMgt_list.jqGrid(
        'navButtonAdd',
        '#UserMgt_pager',
        {
            caption:'',
            title:lbl_Add,
            buttonicon :'ui-icon-plus',
            onClickButton:function(){editRow(-1);}
        });

        UserMgt_list.jqGrid(
        'navButtonAdd',
        '#UserMgt_pager',
        {
            caption:'',
            title:lbl_Delete,
            buttonicon :'ui-icon-trash',
            onClickButton:function(){
                var ids = UserMgt_list.jqGrid('getGridParam','selarrrow');
                if(ids && ids.length > 0){
                    dlg_DeleteConfirm(function(){
                        $.ajax({
                          type: 'POST',
                          url: 'security/UserMgt.action?act='+ACT_DELETE,
                          data: {'ids':ids.toString()},
                          success: function(resTx){
                            if(resTx.success){
                                $(ids).each(function(){
                                    UserMgt_list.jqGrid('setSelection', this);
                                    UserMgt_list.jqGrid('delRowData', this);
                                });
//                                $(resTx.deletedIds).each(function(){
//                                    UserMgt_list.jqGrid('setSelection', this);
//                                    UserMgt_list.jqGrid('delRowData', this);
//                                });
//                                if(resTx.showMsg) dlg_Message(resTx.showMsg);
                            }else{
                                dlg_Error(resTx.info);
                            }
                          },
                          dataType: 'json'
                        });

                    });
                }
            }
        });

    }

    var currenteditid = null;
    function editRow(id){
        if(id == -1){
            var existrow = UserMgt_list.find('tr[id='+id+']');
            if(!existrow || existrow.length < 1){
                var datarow = {'name':''};// TODO:MODIFY ROW DATA
                var su=UserMgt_list.jqGrid('addRowData',id,datarow);
                if(!su) return;
//                UserMgt_list.jqGrid('setSelection',id);
            }
        }
        if(id){
            currenteditid = id;
            if(id!==lastsel){
                if(lastsel)UserMgt_list.jqGrid('restoreRow',lastsel);
                lastsel=id;
            }
            UserMgt_list.jqGrid('editRow',id,true,pickSpecialCols,function(res) {
                var repTx = JSON.parse(res.responseText);
                if(repTx.success){
                    if(repTx.id && repTx.id != id){// new: id==id, update: id!=id
                        //TODO: update data from server side
//                        UserMgt_list.jqGrid('setRowData',id,{
//                            'code':(repTx.code)? repTx.code : ''
//                        });
                    }
                    return true;
                }else{
                    dlg_Error(repTx.info);
                    return false;
                }
             },null,null,function(_id, res){
                currenteditid = null;
                UserMgt_list.jqGrid('setRowData',id,{
                    'password':'********' //never show password
                });
                if(_id != -1) return;//it's update
                var existrow =  UserMgt_list.find('tr[id='+_id+']');
                if(existrow && existrow.length > 0){
                    var repTx = JSON.parse(res.responseText);
                    if(repTx.id && repTx.id != _id) existrow.attr('id', repTx.id);
                }
             },null,function(_id, res){
                currenteditid = null;
             });
        }
    }

    function pickSpecialCols(id){
//        $('#'+id+'_password',UserMgt_list).html('<input type="password"/>');
//        $('#'+id+'_fieldname','#UserMgt_list').datepicker();
    }

    function vld_name(val){
        var regex = new RegExp(/^([\u4e00-\u9fa5]|[0-9]|[a-z]|[A-Z]|[ _-]){1,25}$/g);
        if(regex.test(val)) {
            return [true,'',''];
        } else {
            return [false," : '"+lbl_Name+"'-- "+lbl_vld_err_name,''];
        }
    }

}


